<template>
  <view class="withdraw-container">
    
    <!-- 余额信息 -->
    <view class="balance-card">
      <view class="balance-header">
        <text class="title">可提现余额</text>
      </view>
      <view class="balance-amount">
        <text>¥{{ balanceInfo.availableBalance }}</text>
      </view>
      <view class="balance-footer">
        <text class="tip">提现金额将在1-3个工作日内到账</text>
        <text class="view-record" @click="viewRecords">提现记录 ></text>
      </view>
    </view>
    
    <!-- 提现表单 -->
    <view class="withdraw-form">
      <view class="form-title">
        <text>提现信息</text>
      </view>
      
      <!-- 提现方式 -->
      <view class="form-item">
        <text class="item-label">提现方式</text>
        <picker 
          class="form-picker" 
          mode="selector" 
          :range="withdrawMethods" 
          range-key="name"
          :value="withdrawMethodIndex" 
          @change="onMethodChange"
        >
          <view class="picker-content">
            <view class="method-item">
              <image 
                class="method-icon" 
                :src="formData.method.icon" 
                mode="aspectFit"
              ></image>
              <text class="method-name">{{ formData.method.name }}</text>
            </view>
            <uni-icons type="arrowright" size="20" color="#999"></uni-icons>
          </view>
        </picker>
      </view>
      
      <!-- 提现金额 -->
      <view class="form-item">
        <text class="item-label">提现金额</text>
        <view class="amount-input">
          <text class="prefix">¥</text>
          <input 
            type="digit" 
            v-model="formData.amount" 
            placeholder="请输入提现金额"
            placeholder-class="placeholder"
            @input="onAmountInput"
          />
          <button 
            class="all-btn" 
            size="mini" 
            @click="setAllAmount"
          >全部提现</button>
        </view>
        <view class="amount-tips">
          <text class="error" v-if="amountError">{{ amountError }}</text>
          <text class="fee" v-else>手续费: ¥{{ withdrawFee.toFixed(2) }}，实际到账: ¥{{ actualAmount.toFixed(2) }}</text>
        </view>
      </view>
      
      <!-- 收款账号 -->
      <view class="form-item" v-if="formData.method.type === 'bank'">
        <text class="item-label">银行卡号</text>
        <input 
          class="form-input" 
          v-model="formData.bankNumber" 
          type="number" 
          placeholder="请输入银行卡号"
          placeholder-class="placeholder"
        />
      </view>
      <view class="form-item" v-if="formData.method.type === 'bank'">
        <text class="item-label">开户银行</text>
        <input 
          class="form-input" 
          v-model="formData.bankName" 
          placeholder="请输入开户银行"
          placeholder-class="placeholder"
        />
      </view>
      <view class="form-item" v-if="formData.method.type === 'bank'">
        <text class="item-label">开户姓名</text>
        <input 
          class="form-input" 
          v-model="formData.realName" 
          placeholder="请输入开户姓名"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="form-item" v-if="formData.method.type === 'alipay'">
        <text class="item-label">支付宝账号</text>
        <input 
          class="form-input" 
          v-model="formData.alipayAccount" 
          placeholder="请输入支付宝账号"
          placeholder-class="placeholder"
        />
      </view>
      <view class="form-item" v-if="formData.method.type === 'alipay'">
        <text class="item-label">真实姓名</text>
        <input 
          class="form-input" 
          v-model="formData.realName" 
          placeholder="请输入真实姓名"
          placeholder-class="placeholder"
        />
      </view>
      
      <!-- 提现按钮 -->
      <button 
        class="submit-btn" 
        :class="{disabled: !canSubmit}" 
        :disabled="!canSubmit"
        @click="submitWithdraw"
      >申请提现</button>
    </view>
    
    <!-- 提现规则 -->
    <view class="withdraw-rules">
      <text class="rules-title">提现规则</text>
      <view class="rules-content">
        <view class="rule-item" v-for="(rule, index) in rules" :key="index">
          <text class="rule-index">{{ index + 1 }}.</text>
          <text class="rule-text">{{ rule }}</text>
        </view>
      </view>
    </view>
    
    <!-- 提现确认弹窗 -->
    <uni-popup ref="confirmPopup" type="dialog">
      <uni-popup-dialog 
        type="info" 
        title="确认提现" 
        :content="confirmContent" 
        :duration="0"
        :before-close="true" 
        @confirm="confirmWithdraw" 
        @close="cancelWithdraw"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 余额信息
const balanceInfo = ref({
  availableBalance: '1256.80',
  frozenBalance: '200.00',
  totalIncome: '3450.50'
})

// 提现方式
const withdrawMethods = ref([
  { 
    type: 'alipay', 
    name: '支付宝', 
    icon: '/static/images/alipay.png',
    feeRate: 0.01,  // 1%手续费
    minAmount: 10   // 最低提现金额
  },
  { 
    type: 'bank', 
    name: '银行卡', 
    icon: '/static/images/bank.png',
    feeRate: 0.015, // 1.5%手续费
    minAmount: 100  // 最低提现金额
  }
])

// 表单数据
const formData = ref({
  method: {},
  amount: '',
  bankNumber: '',
  bankName: '',
  alipayAccount: '',
  realName: ''
})

// 提现规则
const rules = ref([
  '最低提现金额为10元（支付宝）或100元（银行卡）',
  '单笔最高提现金额为5000元',
  '每日最多可提现3次',
  '提现手续费：支付宝1%，银行卡1.5%',
  '提现申请将在1-3个工作日内处理',
  '如有疑问，请联系客服咨询'
])

// 提现方式索引
const withdrawMethodIndex = ref(0)

// 金额错误提示
const amountError = ref('')

// 加载状态
const loading = ref(false)

// 计算属性
const withdrawFee = computed(() => {
  if (!formData.value.method.feeRate || !formData.value.amount) return 0
  return parseFloat(formData.value.amount) * formData.value.method.feeRate
})

const actualAmount = computed(() => {
  if (!formData.value.amount) return 0
  return parseFloat(formData.value.amount) - withdrawFee.value
})

const canSubmit = computed(() => {
  return (
    formData.value.amount && 
    !amountError.value && 
    (formData.value.method.type === 'alipay' ? formData.value.alipayAccount && formData.value.realName : 
     formData.value.method.type === 'bank' ? formData.value.bankNumber && formData.value.bankName && formData.value.realName : 
     false)
  )
})

const confirmContent = computed(() => {
  return `提现金额: ¥${formData.value.amount}\n手续费: ¥${withdrawFee.value.toFixed(2)}\n实际到账: ¥${actualAmount.value.toFixed(2)}\n提现到: ${formData.value.method.name}`
})

// 页面加载
onLoad(() => {
  // 默认选择第一个提现方式
  formData.value.method = withdrawMethods.value[0]
})

// 提现方式变更
const onMethodChange = (e) => {
  const index = e.detail.value
  withdrawMethodIndex.value = index
  formData.value.method = withdrawMethods.value[index]
  // 清空金额错误
  amountError.value = ''
  // 验证金额
  if (formData.value.amount) {
    validateAmount(formData.value.amount)
  }
}

// 金额输入处理
const onAmountInput = (e) => {
  validateAmount(e.detail.value)
}

// 验证金额
const validateAmount = (value) => {
  if (!value) {
    amountError.value = ''
    return
  }
  
  const amount = parseFloat(value)
  const available = parseFloat(balanceInfo.value.availableBalance)
  const minAmount = formData.value.method.minAmount
  
  if (isNaN(amount) || amount <= 0) {
    amountError.value = '请输入有效的金额'
  } else if (amount < minAmount) {
    amountError.value = `最低提现金额为¥${minAmount}`
  } else if (amount > available) {
    amountError.value = '提现金额不能超过可用余额'
  } else if (amount > 5000) {
    amountError.value = '单笔最高提现金额为¥5000'
  } else {
    amountError.value = ''
  }
}

// 全部提现
const setAllAmount = () => {
  const available = parseFloat(balanceInfo.value.availableBalance)
  formData.value.amount = available > 5000 ? '5000' : available.toString()
  validateAmount(formData.value.amount)
}

// 提交提现申请
const submitWithdraw = () => {
  if (!canSubmit.value) return
  
  // 弹出确认框
  this.$refs.confirmPopup.open()
}

// 确认提现
const confirmWithdraw = (done) => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    loading.value = false
    done()
    
    uni.showToast({
      title: '提现申请已提交',
      icon: 'success'
    })
    
    // 重置表单
    resetForm()
    
    // 模拟更新余额
    balanceInfo.value.availableBalance = (parseFloat(balanceInfo.value.availableBalance) - parseFloat(formData.value.amount)).toFixed(2)
    balanceInfo.value.frozenBalance = (parseFloat(balanceInfo.value.frozenBalance) + parseFloat(formData.value.amount)).toFixed(2)
  }, 1500)
}

// 取消提现
const cancelWithdraw = (done) => {
  done()
}

// 重置表单
const resetForm = () => {
  formData.value.amount = ''
  formData.value.bankNumber = ''
  formData.value.bankName = ''
  formData.value.alipayAccount = ''
  formData.value.realName = ''
  amountError.value = ''
}

// 查看提现记录
const viewRecords = () => {
  uni.navigateTo({
    url: '/pages/wallet/withdraw-records'
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>

.withdraw-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $light-bg;
}

.balance-card {
  background: linear-gradient(135deg, $primary-color, $secondary-color);
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  margin: 20rpx;
  color: $text-color-inverse;
  
  .balance-header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: $font-size-30rpx;
      font-weight: bold;
    }
  }
  
  .balance-amount {
    font-size: 60rpx;
    font-weight: bold;
    margin-bottom: 40rpx;
  }
  
  .balance-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .tip {
      font-size: $font-size-24rpx;
      opacity: 0.8;
    }
    
    .view-record {
      font-size: $font-size-24rpx;
      text-decoration: underline;
    }
  }
}

.withdraw-form {
  background-color: $white-bg;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 0 30rpx;
  
  .form-title {
    font-size: $font-size-30rpx;
    font-weight: bold;
    color: $text-color;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
  }
  
  .form-item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    
    .item-label {
      font-size: $font-size-28rpx;
      color: $text-color;
      margin-bottom: 20rpx;
      display: block;
    }
    
    .form-picker {
      .picker-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .method-item {
          display: flex;
          align-items: center;
          
          .method-icon {
            width: 40rpx;
            height: 40rpx;
            margin-right: 15rpx;
          }
          
          .method-name {
            font-size: $font-size-28rpx;
            color: $text-color;
          }
        }
      }
    }
    
    .amount-input {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #eee;
      padding-bottom: 10rpx;
      
      .prefix {
        font-size: $font-size-36rpx;
        color: $text-color;
        margin-right: 10rpx;
      }
      
      input {
        flex: 1;
        font-size: $font-size-36rpx;
        color: $text-color;
        height: 80rpx;
      }
      
      .all-btn {
        background-color: $light-bg;
        color: $primary-color;
        border: none;
        font-size: $font-size-24rpx;
        height: 50rpx;
        line-height: 50rpx;
      }
    }
    
    .amount-tips {
      margin-top: 15rpx;
      
      .error {
        font-size: $font-size-24rpx;
        color: #F44336;
      }
      
      .fee {
        font-size: $font-size-24rpx;
        color: $text-color-666;
      }
    }
    
    .form-input {
      font-size: $font-size-28rpx;
      color: $text-color;
      height: 60rpx;
      border-bottom: 1rpx solid #eee;
      padding-bottom: 10rpx;
    }
  }
  
  .submit-btn {
    background-color: $primary-color;
    color: $text-color-inverse;
    font-size: $font-size-32rpx;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 45rpx;
    margin: 40rpx 0;
    
    &.disabled {
      opacity: 0.6;
      background-color: #ccc;
    }
  }
}

.withdraw-rules {
  background-color: $white-bg;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 30rpx;
  
  .rules-title {
    font-size: $font-size-28rpx;
    font-weight: bold;
    color: $text-color;
    display: block;
    margin-bottom: 20rpx;
  }
  
  .rules-content {
    .rule-item {
      display: flex;
      margin-bottom: 15rpx;
      
      .rule-index {
        font-size: $font-size-26rpx;
        color: $primary-color;
        margin-right: 10rpx;
      }
      
      .rule-text {
        font-size: $font-size-26rpx;
        color: $text-color;
        flex: 1;
      }
    }
  }
}

.placeholder {
  color: #ccc;
  font-size: $font-size-28rpx;
}
</style>